package com.sky.controller.admin;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.sky.JWT.JWTUtils;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.EmployeeService;
import com.sky.vo.EmployeeLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * 员工管理
 */
@RestController
@RequestMapping("/admin/employee")
@Slf4j
@Api(tags = "员工相关接口")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 注册
     *
     * @param employeeDTO
     * @return
     */
    @PostMapping("/register")
    @ApiOperation(value = "员工注册")
    public Result<EmployeeLoginVO> login(@RequestBody EmployeeDTO employeeDTO) {
        log.info("员工注册：{}", employeeDTO);
        employeeService.save(employeeDTO);
        return Result.success();
    }
    /**
     * 登录
     *
     * @param employeeLoginDTO
     * @return
     */
    @PostMapping("/login")
    @ApiOperation(value = "员工登录")
    public Result<EmployeeLoginVO> login(@RequestBody EmployeeLoginDTO employeeLoginDTO) {
        log.info("员工登录：{}", employeeLoginDTO);

        Employee employee = employeeService.login(employeeLoginDTO);

        //登录成功后，生成jwt令牌
        String token = JWTUtils.getToken(employee);

        // 将 token 存入 Redis，设置过期时间（例如 30 分钟）
        redisTemplate.opsForValue().set("token:" + employee.getId(), token, 30, TimeUnit.MINUTES);

        EmployeeLoginVO employeeLoginVO = EmployeeLoginVO.builder()
                .id(employee.getId())
                .userName(employee.getUsername())
                .token(token)
                .role(employee.getRole())
                .build();

        return Result.success(employeeLoginVO);
    }


    @RequiresRoles("管理员")
    @PostMapping()
    @ApiOperation(value = "新增员工")
    public Result save(@RequestBody EmployeeDTO employeeDTO) {
        employeeService.save(employeeDTO);
        return Result.success();
    }
    /**
     * 退出
     *
     * @return
     */
    @PostMapping("/logout")
    @ApiOperation(value = "员工退出")
    public Result<String> logout(HttpServletRequest request) {
        String token = request.getHeader("token");

        if (token == null || token.isEmpty()) {
            return Result.error("缺少 token，无法完成退出操作");
        }

        try {
            DecodedJWT decodedJWT = JWTUtils.verify(token);
            Long userId = decodedJWT.getClaim("id").asLong();

            // 删除 Redis 中的 Token
            redisTemplate.delete("token:" + userId);

            return Result.success("退出成功");
        } catch (Exception e) {
            return Result.error("无效的 token：" + e.getMessage());
        }
    }
    // 处理未认证请求的控制器
    @GetMapping("/unauthorized/{message}")
    public Result unauthorized(@PathVariable("message") String message) {
        return Result.error(message);
    }

    @RequiresRoles(value={"管理员","普通用户"},logical = Logical.OR)
    @GetMapping("/page")
    @ApiOperation(value = "员工分页查询")
    public Result<PageResult> page(EmployeePageQueryDTO pageQuery){
        PageResult pageResult = employeeService.pageQuery(pageQuery);
        return Result.success(pageResult);
    }

    @RequiresRoles(value={"管理员","普通用户"},logical = Logical.OR)
    @GetMapping("/{id}")
    @ApiOperation(value = "根据ID查找员工")
    public Result<Employee> getById(@PathVariable Long id){
        Employee employee = employeeService.getById(id);
        return Result.success(employee);
    }

    @PutMapping
    @RequiresRoles(value={"管理员","普通用户"},logical = Logical.OR)
    @ApiOperation(value = "编辑员工信息")
    public Result update(@RequestBody EmployeeDTO employeeDTO){
        employeeService.update(employeeDTO);
        return Result.success();
    }

    //设置用户权限
    @RequiresRoles("系统管理员")
    @PutMapping("/setRole/{id}")
    @ApiOperation(value = "设置用户权限")
    public Result setRole(@PathVariable Long id,@RequestParam String role) {
        employeeService.setRole(role, id);
        return Result.success();
    }
}
